package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseSingleButtonDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CertificateNoContent;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.DeleteSuccessMessage;
import com.isunland.managesystem.entity.EmployeeLoanContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.util.HashMap;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * 员工借款详情编辑
 *
 * @author wu
 */
public class EmpoyeeLoanDetailEditFragment extends EmpoyeeLoanFragment {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  protected static final String TAG = EmpoyeeLoanDetailEditFragment.class.getName();
  private EmployeeLoanContent mEmployeeLoanContent;
  private BaseVolleyActivity mActivity;
  private String mCertificateNo;// 单据编号
  private String mExpenseDesc;// 费用摘要
  private String mPoutAmount;// 本次借款金额
  private String mSumBorrow;// 历史借款合计
  private String mRegStaffName;// 借款人
  private String mApplicantName;// 申请人
  private String mApplyTime;// 申请日期
  private String mType;// 类别

  private String mMemberCode;// 会员编码
  private String fileName = "";// 附件名

  @Override public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    mActivity = (BaseVolleyActivity) getActivity();
    mMemberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
    mEmployeeLoanContent = (EmployeeLoanContent) getArguments().getSerializable(EXTRA_VALUE);

    if (mEmployeeLoanContent != null) {
      mCertificateNo = mEmployeeLoanContent.getCertificateNo();
      mExpenseDesc = mEmployeeLoanContent.getExpenseDesc();
      mPoutAmount = mEmployeeLoanContent.getPoutAmount();
      mSumBorrow = mEmployeeLoanContent.getSumBorrow();
      mRegStaffName = mEmployeeLoanContent.getRegStaffName();
      mApplicantName = mEmployeeLoanContent.getApplicantName();
      mApplyTime = mEmployeeLoanContent.getApplyTime();
      mType = mEmployeeLoanContent.getCertificateName();
    }
    fileName = mEmployeeLoanContent.getFileOriginalName();
    mfileName = fileName;
    selcurFile = mEmployeeLoanContent.getFilePath();
  }

  public void initData() {
    //只有草稿状态获取已有借款合计
    if ((mEmployeeLoanContent.getDataStatus()).equals(DataStatus.NEW)) {
      tvsumBorrow.setText(mSumBorrow);
      getSumBorrow();//获取已有借款合计
    } else {
      tvsumBorrow.setText(mSumBorrow);
    }
    tvcertificateNo.setText(mCertificateNo);
    etexpenseDesc.setText(mExpenseDesc);
    etpoutAmount.setText(mPoutAmount);
    tvloanPerson.setText(mRegStaffName);
    tvloanProposer.setText(mApplicantName);// 申请人
    tvloanDate.setText(mApplyTime);// 申请时间

    //开户行
    etpayeeBank.setText(mEmployeeLoanContent.getPayeeBank());
    etpayeeAccname.setText(mEmployeeLoanContent.getPayeeAccname());
    etpayeeAccount.setText(mEmployeeLoanContent.getPayeeAccount());
    if (!TextUtils.isEmpty(mEmployeeLoanContent.getFileOriginalName())) {
      //附件
      mTvExtra.setText(mEmployeeLoanContent.getFileOriginalName());
      //点击附件名，下载附件
      mTvExtra.setOnClickListener(new OnClickListener() {

        @Override public void onClick(View v) {
          ExtraDownLoadDialogFragment dialog = null;
          if (TextUtils.isEmpty(mFilePath)) {
            dialog = ExtraDownLoadDialogFragment.newInstance("", selcurFile);
          } else {
            dialog = ExtraDownLoadDialogFragment.newInstance(mFilePath, "");
          }

          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.show(fm, "");
        }
      });
    }
  }

  public void getSumBorrow() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_EMPLOYEE_LOAN_DETAIL);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("certificateCode", mEmployeeLoanContent.getCertificateCode());
    params.put("userJobNo", mCurrentUser.getJobNumber());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        CertificateNoContent[] array = new Gson().fromJson(arg0, CertificateNoContent[].class);
        CertificateNoContent mNoContent = array[0];
        tvsumBorrow.setText(mNoContent.getSumBorrow());//已有借款合计
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_confirm:

        if (TextUtils.isEmpty(etpoutAmount.getText().toString())) {
          Toast.makeText(getActivity(), R.string.borrowMoney, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(tvcertificateNo.getText().toString())) {
          Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
        } else {
          //				postSave();
          //选择新附件，先删除原始附件
          //				if (!TextUtils.isEmpty(mTvExtra.getText().toString()) && !TextUtils.isEmpty(mfileName) && !TextUtils.isEmpty(mDocPath)) {
          //					Log.i("借款附件===","新附件上传");
          //					showDialog();
          //					//上传新附件
          ////					volleyExtra();
          //					volleyDelete();
          //				}
          //				//附件为空时
          //				if (TextUtils.isEmpty(mTvExtra.getText().toString())&& TextUtils.isEmpty(mfileName) && TextUtils.isEmpty(mDocPath)) {
          //					Log.i("借款附件===","附件上传为空");
          //					selcurFile="";
          //					mfileName="";
          //					postSave();
          //
          //				}
          //				//附件没有修改时
          //				else {
          //					Log.i("借款附件===","附件没有修改");
          //					postSave();
          //				}
          //附件为空时
          if (TextUtils.isEmpty(mfileName) && TextUtils.isEmpty(mFilePath)) {
            Log.i("借款附件===", "附件上传为空");
            selcurFile = "";
            mfileName = "";
            postSave();
          }
          //没选新附件
          else if (!TextUtils.isEmpty(mfileName) && TextUtils.isEmpty(mFilePath)) {
            Log.i("借款附件===", "附件没修改");
            postSave();
          }
          //选新附件
          else {
            Log.i("借款附件===", "上传新附件");
            volleyExtra();
          }
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //删除附件
  private void volleyDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_FILE);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("selcurFile", selcurFile);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        DeleteSuccessMessage result =
            new Gson().fromJson(new String(arg0), DeleteSuccessMessage.class);
        try {

          SuccessMessage delResult = new Gson().fromJson(new String(arg0), SuccessMessage.class);
          //删除成功
          if (delResult != null && delResult.getResult() != null && result.getResult()
              .equals("1")) {
            Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
            volleyExtra();//上传新附件
          } else {
            Toast.makeText(getActivity(), "文件不存在", Toast.LENGTH_SHORT).show();
            volleyExtra();//上传新附件
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
          Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        } catch (NotFoundException e) {
          e.printStackTrace();
          Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
      }
    });
  }

  private void volleyExtra() {

    new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_UPLOAD_FILE,
        "r_expense_inexp_main", mEmployeeLoanContent.getId(), new myUpLoadHandler(), false);
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {
    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      //			MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          //					Toast.makeText(getActivity(), R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
          // 上传成功,再上传数据
          selcurFile = result.getMessage().toString();
          selcurFile = selcurFile.replace("\\", "/");
          LogUtil.i("selcurFile==" + selcurFile);
          postSave();
        } else {
          MyUtils.dismissDialog();
          //					Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
          //重命名，重新上传文件
          //					mDocPath=FileUtil.renameFile(mDocPath);
          //					mfileName=FileUtil.getFileNameByFilePath(mDocPath);
          //					LogUtil.i("重命名mFilePath==="+mDocPath);
          //					//刷新sd卡
          //					MediaScannerConnection.scanFile(getActivity(), new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()+"/"+mfileName}, null, null);
          //					new FileNetWorkUtil(getActivity()).upLoadFile(mDocPath, ApiConst.URL_UPLOAD_FILE, "r_expense_inexp_main",mEmployeeLoanContent.getId(), new myUpLoadHandler(), false);
          DialogFragment dialog = null;
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog = BaseSingleButtonDialogFragment.newInstance(R.string.rename_file,
              R.string.restart_title);
          dialog.setTargetFragment(EmpoyeeLoanDetailEditFragment.this, REQUEST_CHONG_FU);
          dialog.show(fm, "");
        }
      } catch (JsonSyntaxException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      } catch (NotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }
    }
  }

  private void postSave() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PESONAL_SAVE);

    HashMap<String, String> params = new HashMap<String, String>();

    // 更新content
    mEmployeeLoanContent.setCertificateNo(tvcertificateNo.getText().toString());
    mEmployeeLoanContent.setExpenseDesc(etexpenseDesc.getText().toString());
    mEmployeeLoanContent.setPoutAmount(etpoutAmount.getText().toString());
    mEmployeeLoanContent.setSumBorrow(tvsumBorrow.getText().toString());
    mEmployeeLoanContent.setRegStaffName(tvloanPerson.getText().toString());
    mEmployeeLoanContent.setApplicantName(tvloanProposer.getText().toString());
    mEmployeeLoanContent.setApplyTime(tvloanDate.getText().toString());

    //开户行
    mEmployeeLoanContent.setPayeeBank(etpayeeBank.getText().toString());
    mEmployeeLoanContent.setPayeeAccname(etpayeeAccname.getText().toString());
    mEmployeeLoanContent.setPayeeAccount(etpayeeAccount.getText().toString());
    //选择新附件时
    //		if (!TextUtils.isEmpty(mDocPath)) {
    //附件
    mEmployeeLoanContent.setFileOriginalName(mfileName);
    mEmployeeLoanContent.setFilePath(selcurFile);
    //		}
    params.put("json", new Gson().toJson(mEmployeeLoanContent));
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("certificateCode", mEmployeeLoanContent.getCertificateCode());
    params.put("regJobNo", mCurrentUser.getJobNumber());
    params.put("type", "mobile");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i(TAG, "response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
          SuccessMessage success = result[0];
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), success.getMessage(), Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), success.getMessage(), Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), success.getMessage(), Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override protected void setTitle() {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.costDetailEdit);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_CHONG_FU) {
      return;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public static Fragment newInstance(EmployeeLoanContent employeeLoanContent) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, employeeLoanContent);
    EmpoyeeLoanDetailEditFragment fragment = new EmpoyeeLoanDetailEditFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}
